<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>双向链表-方法封装</title>
</head>
<body>
  <script src="https://cdn.bootcss.com/lodash.js/4.17.15/lodash.core.min.js"></script>
  <script>
      /**
       * 双向链表：头指针、尾指针、data
      */
      function DobuleLinkList () {
        // 定义初始化数据
        this.head = null;
        this.tail = null;
        this.length = 0;

      }
      // 1. append()
      DobuleLinkList.prototype.append = function (data) {
        // 1. 定义当前节点
        const currNode = {
          data,
          prev: null,
          next: null,
        }
        // 没有节点信息时
        if (!this.length) {
          this.head = currNode
          this.tail = currNode;
          this.length ++;
          return false;
        }
        // 2. 追加节点
        currNode.prev = this.tail;
        this.tail.next = currNode;
        this.tail = currNode;
        // 长度+1
        this.length ++;
      }

      // 2. toForwardString(), 从后向前拼接data
      DobuleLinkList.prototype.toForwardString = function () {
        let current = this.tail, str = '';
        while (current) {
          if (_.isObject(current.data)) {
            current.data = JSON.stringify(current.data);
          }
          str += current.data;
          current = current.prev;
        }
        return str;
      }

      // 3. toBackwardString(), 从前向后拼接data
      DobuleLinkList.prototype.toBackwardString = function () {
        let current = this.head, str = '';
        while (current) {
          if (_.isObject(current.data)) {
            current.data = JSON.stringify(current.data);
          }
          str += current.data;
          current = current.next;
        }
        return str;
      }
      
      
      // 4. toString()，和toBackwardString()方法一样
      DobuleLinkList.prototype.toString = function () {
        return this.toBackwardString();
      }

      // 5. 
      DobuleLinkList.prototype.l = function () {
        
      }

      const doubleLinkList = new DobuleLinkList();
      doubleLinkList.append(1);
      doubleLinkList.append('cs');
      doubleLinkList.append(3);
      doubleLinkList.append({a: 4});
      doubleLinkList.append([5]);
      console.log(doubleLinkList);
      console.log('toForwardString', doubleLinkList.toForwardString());
      console.log('toBackwardString', doubleLinkList.toBackwardString());
      console.log('toString', doubleLinkList.toString());
    </script>
</body>
</html>